//
//  KABMineEntryMsgVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/4/14.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMineEntryMsgVC.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "KABModel.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABRCIMMsgListVC.h"
#import "KABMineMsgVC.h"
#import "KABMineMsgEntryTCell.h"
#import "UIColor+XDHex.h"
#import <RongIMKit/RongIMKit.h>

@interface KABMineEntryMsgVC ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSArray<UIColor *> *cellColorArray;
@property (strong, nonatomic) NSArray<NSString *> *cellTitleArray;
@property (strong, nonatomic) NSArray<UIImage *> *cellImgArray;

@end

static NSString *const kReuseCellId = @"KABMineMsgEntryTCell";

@implementation KABMineEntryMsgVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self requestCosLikeAndCommentCnt];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"我的消息";
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 140.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellColorArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMineMsgEntryTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    [cell.leftBtn setBackgroundColor:self.cellColorArray[indexPath.row]];
    [cell.leftBtn setImage:self.cellImgArray[indexPath.row] forState:UIControlStateNormal];
    cell.leftTitleLabel.text = self.cellTitleArray[indexPath.row];
    NSString *cntStr = @"";
    if (indexPath.row == 0) {   // IM未读消息的数量
        if ([RCIMClient sharedRCIMClient].getTotalUnreadCount > 0) {
            cntStr = [NSString stringWithFormat:@"%d条", [RCIMClient sharedRCIMClient].getTotalUnreadCount];
        }
    } else if (indexPath.row == 1) {    // 点赞的数量
        if ([KABModel sharedInstance].mineNewMsg.new_praise_number > 0) {
            cntStr = [NSString stringWithFormat:@"%zd个", [KABModel sharedInstance].mineNewMsg.new_praise_number];
        }
    } else {    // 回复or评论的数量
        NSInteger totalCnt = [KABModel sharedInstance].mineNewMsg.new_reply_number + [KABModel sharedInstance].mineNewMsg.new_comment_number;
        if (totalCnt > 0) {
            cntStr = [NSString stringWithFormat:@"%zd条", totalCnt];
        }
    }
    cell.rightDetailLabel.text = cntStr;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
        KABRCIMMsgListVC *listVC = [[KABRCIMMsgListVC alloc] init];
        [self showViewController:listVC sender:nil];
        return;
    }
    
    KABMineMsgVC *msgVC = [[KABMineMsgVC alloc] init];
    msgVC.viewType = indexPath.row - 1;
    [self showViewController:msgVC sender:nil];
}

#pragma mark - event response
#pragma mark - private methods
- (void)refreshWholeView {
//    // 尾部加载更多的显示
//    if (self.msgList.totalLoad) {
//        [self.tableView.mj_footer endRefreshingWithNoMoreData];
//    } else {
//        [self.tableView.mj_footer resetNoMoreData];
//    }
    
    [self.tableView reloadData];
}

#pragma mark - network request
- (void)requestCosLikeAndCommentCnt {
    // 获取未读消息(点赞、评论、回复)的数量
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiNewMessage] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求未读消息返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] mineNewMsgWithDictionary:responseObject];
            [self refreshWholeView];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求未读消息失败：%@", error);
    }];
}

#pragma mark - getters and setters
- (NSArray<UIColor *> *)cellColorArray {
    if (!_cellColorArray) {
        _cellColorArray = @[[UIColor xd_colorWithHex:0x56A4FF],
                            [UIColor xd_colorWithHex:0xF4984E],
                            [UIColor xd_colorWithHex:0x6286F5]];
    }
    return _cellColorArray;
}

- (NSArray<UIImage *> *)cellImgArray {
    if (!_cellImgArray) {
        _cellImgArray = @[[UIImage imageNamed:@"mine_msg_im"],
                          [UIImage imageNamed:@"mine_msg_like"],
                          [UIImage imageNamed:@"mine_msg_comment"]];
    }
    return _cellImgArray;
}

- (NSArray<NSString *> *)cellTitleArray {
    if (!_cellTitleArray) {
        _cellTitleArray = @[@"IM", @"点赞", @"评论"];
    }
    return _cellTitleArray;
}

@end
